// pages/exhition/exhibition.js
const bgMusic = wx.getBackgroundAudioManager();
const { formatAudio, timestr2sec } = require('../../utils/util.js');
const WxParse = require('../../utils/wxParse/wxParse.js');
const {
  BH_ExhibitDetail,
  visit_exhibit
} = require('../../http/interface.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTime: '',
    maxTime: '', //总时长（字符串）
    max: '', //总时长（秒）
    playing: false, //正在播放,
    curSwiperIndex:1,
    offset:0,
    language:1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    var exhibit_id = options.id;
    this.id = options.id;
    var token = wx.getStorageSync('api_token')
    BH_ExhibitDetail(exhibit_id, token).then(res => {
      that.setData({
        exhibit: res.data,
        currentTime: formatAudio(0),
        offest:0,
        max: timestr2sec(res.data.audio_time),
        maxTime: formatAudio(timestr2sec(res.data.audio_time))
      });

      that.audioInit();
      WxParse.wxParse('content', 'html', res.data.content.replace(/\n/g, '<br/>'), that);
    })
    visit_exhibit(token,exhibit_id).then(res=>{
     
    })
  },
  changeLanguage(){
    if(this.data.language==1){
      this.setData({
        'language':2
      })
      this.data.language=2
    }else{
      this.setData({
        'language':1
      })
     
    }
    var token = wx.getStorageSync('api_token');
    var that = this;
    BH_ExhibitDetail(this.id, token,this.data.language).then(res => {
      if(res.status==1){
        that.setData({
          exhibit: res.data,
          currentTime: formatAudio(0),
          offest:0,
          max: timestr2sec(res.data.audio_time),
          maxTime: formatAudio(timestr2sec(res.data.audio_time))
        });
        WxParse.wxParse('content', 'html', res.data.content.replace(/\n/g, '<br/>'), that);
      }else{
        wx.showToast({
          title: '暂无英文版',
          icon:"none"
        })
        this.setData({
          'language':1
        })
      }
    })
  },
  //轮播图
  swiperChange: function (e) {
    this.setData({
      curSwiperIndex: ++e.detail.current
    })
  },
  //音频初始化
  audioInit() {
    var that = this;

    bgMusic.onPlay(() => {
      // console.log('详情页开播了');
      bgMusic.duration //类似初始化-必须触发-不触发此函数延时也获取不到！！！！！！！！！！！！！！！

      wx.setStorage({
        key: 'bjaudioId',
        data: that.data.exhibit,
      })
      setTimeout(function () {
        that.setData({
          playing: true,
          // 获取时长
          maxTime: formatAudio(Math.round(bgMusic.duration)),
        })
      }, 100) //这里设置延时获取
    });

    bgMusic.onPause(() => {
      // console.log('详情页暂停了');
      that.setData({
        playing: false,
      });
    });

    bgMusic.onTimeUpdate(() => {
      const bjaudioId = wx.getStorageSync('bjaudioId');
     
      if (!bgMusic.paused) {

        if (bgMusic.src == that.data.exhibit.audio && bjaudioId.exhibit_id == that.data.exhibit.exhibit_id) {
          console.log(bgMusic.currentTime)
          that.setData({
            playing: true,
            offset: Math.round(bgMusic.currentTime),
            over:false,
            currentTime: formatAudio(Math.round(bgMusic.currentTime)),
            maxTime: formatAudio(Math.round(bgMusic.duration))
          });
        } else {
          bgMusic.stop()
        }
      }
    });

    bgMusic.onEnded(() => {
      // console.log('详情页播完了');

      const bjaudioId = wx.getStorageSync('bjaudioId');

      that.setData({
        playing: false,
        offset: 0,
        over: true,
      });

      wx.removeStorage({
        key: 'bjaudioId',
        success(res) {
          console.log(res)
        }
      })
    });

    bgMusic.onStop(() => {
      // console.log('详情页关闭了');
      that.setData({
        playing: false,
        over: true,
      });
    });

  },

  play() { //播放讲解词
    var that = this;
    var bjaudioId = wx.getStorageSync('bjaudioId');
    if (that.data.playing) {
      bgMusic.pause();
    } else {
      if (bgMusic.src == that.data.exhibit.audio && bjaudioId.exhibit_id == that.data.exhibit.exhibit_id) {
        if (that.data.over) { //播放完成后需要再赋值一次才能再播放
          bgMusic.string = '滨海科技馆';
          bgMusic.src = that.data.exhibit.audio;
          bgMusic.title = that.data.exhibit.exhibit_name;
          bgMusic.coverImgUrl = that.data.exhibit.exhibit_imgs[0]; //封面图 URL，用于做原生音频播放器背景图。
        } else {
          bgMusic.play();
        }
      } else {
        // 首次播放
        if (that.data.exhibit.audio) {
          bgMusic.string = '滨海科技馆';
          bgMusic.src = that.data.exhibit.audio; //默认为空字符串，当设置了新的 src 时，会自动开始播放，目前支持的格式有 m4a, aac, mp3, wav。
          bgMusic.title = that.data.exhibit.exhibit_name;
          bgMusic.coverImgUrl = that.data.exhibit.exhibit_imgs[0];
          wx.setStorage({
            key: 'bjaudioId',
            data: that.data.exhibit,
          })
        } else {
          wx.showToast({
            title: '暂无资源',
            icon: 'none'
          });
        }
      }
    };
  },
  sliderChange(e) {
    var that = this;
    if (e.detail.value) {
        if (!that.data.playing) {
            bgMusic.string = '滨海科技馆';
            bgMusic.src = that.data.exhibit.audio;
            bgMusic.title = that.data.exhibit.exhibit_name;
            bgMusic.coverImgUrl = that.data.exhibit.exhibit_imgs[0];
            wx.setStorage({
                key: 'bjaudioId',
                data: that.data.exhibit,
            })
            setTimeout(function() {
                bgMusic.seek(e.detail.value);
            }, 100)
        } else {
            bgMusic.seek(e.detail.value);
        }
    }
},
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})